package com.lql.aicode.controller;


import com.lql.aicode.annotation.AuthCheck;
import com.lql.aicode.common.BaseResponse;
import com.lql.aicode.common.DeleteRequest;
import com.lql.aicode.common.ResultUtils;
import com.lql.aicode.constant.UserConstant;
import com.lql.aicode.exception.BusinessException;
import com.lql.aicode.exception.ErrorCode;
import com.lql.aicode.exception.ThrowUtils;
import com.lql.aicode.model.dto.interview.InterviewQueryRequest;
import com.lql.aicode.model.dto.interview.InterviewQuestionRequest;
import com.lql.aicode.model.entity.InterviewReport;
import com.lql.aicode.model.entity.User;
import com.lql.aicode.model.vo.interview.DetailedInterviewReportVO;
import com.lql.aicode.model.vo.interview.InterviewQuestionVO;
import com.lql.aicode.model.vo.interview.InterviewReportVO;
import com.lql.aicode.service.InterviewReportService;
import com.lql.aicode.service.UserService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/interview")
public class InterviewReportController {

    @Resource
    private InterviewReportService interviewReportService;
    @Resource
    private UserService userService;


    /**
     * 生成面试题
     *
     * @param interviewType 岗位类型
     * @return 岗位面试题
     */
    @GetMapping("/generateQuestions")
    public BaseResponse<List<InterviewQuestionVO>> generateInterviewQuestion(String interviewType, HttpServletRequest request) {
        ThrowUtils.throwIf(interviewType == null, ErrorCode.PARAMS_ERROR);
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        List<InterviewQuestionVO> interviewQuestions = interviewReportService.generateInterviewQuestion(interviewType, loginUser);
        return ResultUtils.success(interviewQuestions);
    }

    /**
     * 添加题目的用户回答
     *
     * @param interviewQuestionRequest
     * @return
     */
    @PostMapping("/answer")
    public BaseResponse<Boolean> addAnswer(@RequestBody InterviewQuestionRequest interviewQuestionRequest) {
        ThrowUtils.throwIf(interviewQuestionRequest == null, ErrorCode.PARAMS_ERROR);
        boolean result = interviewReportService.addAnswer(interviewQuestionRequest);
        return ResultUtils.success(result);
    }

    /**
     * 删除报告（用户只能删除自己的报告）
     *
     * @param deleteRequest 删除请求
     * @param request       请求
     * @return 删除结果
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteReport(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterviewReport report = interviewReportService.getById(id);
        ThrowUtils.throwIf(report == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!report.getUserId().equals(loginUser.getId()) && !UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interviewReportService.removeReportId(id);
        return ResultUtils.success(result);
    }

    /**
     * 管理员删除报告
     *
     * @param deleteRequest 删除请求
     * @return 删除结果
     */
    @PostMapping("/admin/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteReportByAdmin(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        InterviewReport report = interviewReportService.getById(id);
        ThrowUtils.throwIf(report == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = interviewReportService.removeReportId(id);
        return ResultUtils.success(result);
    }

    /**
     * 管理员分页获取应用列表
     *
     * @param interviewQueryRequest 查询请求
     * @return 应用列表
     */
    @PostMapping("/admin/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<InterviewReportVO>> listInterviewReportVOByPageByAdmin(@RequestBody InterviewQueryRequest interviewQueryRequest) {
        ThrowUtils.throwIf(interviewQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int pageNum = interviewQueryRequest.getPageNum();
        int pageSize = interviewQueryRequest.getPageSize();
        QueryWrapper queryWrapper = interviewReportService.getQueryWrapper(interviewQueryRequest);
        Page<InterviewReport> interviewReportPage = interviewReportService.page(Page.of(pageNum, pageSize), queryWrapper);
        // 数据封装
        Page<InterviewReportVO> interviewReportVOPage = new Page<>(pageNum, pageSize, interviewReportPage.getTotalRow());
        List<InterviewReportVO> interviewReportVOList = interviewReportService.getInterviewReportVOList(interviewReportPage.getRecords());
        interviewReportVOPage.setRecords(interviewReportVOList);
        return ResultUtils.success(interviewReportVOPage);
    }

    /**
     * 分页获取精选应用列表
     *
     * @param interviewQueryRequest
     * @return 精选应用列表
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<InterviewReportVO>> listInterviewReportVOByPage(@RequestBody InterviewQueryRequest interviewQueryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(interviewQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int pageNum = interviewQueryRequest.getPageNum();
        int pageSize = interviewQueryRequest.getPageSize();

        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);

        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq(InterviewReport::getUserId, loginUser.getId());
        // 分页查询
        Page<InterviewReport> interviewReportPage = interviewReportService.page(Page.of(pageNum, pageSize), queryWrapper);
        // 数据封装
        Page<InterviewReportVO> interviewReportVOPage = new Page<>(pageNum, pageSize, interviewReportPage.getTotalRow());
        List<InterviewReportVO> interviewReportVOList = interviewReportService.getInterviewReportVOList(interviewReportPage.getRecords());
        interviewReportVOPage.setRecords(interviewReportVOList);
        return ResultUtils.success(interviewReportVOPage);
    }

    // 根据id获取详细的报告
    @GetMapping("/report")
    public BaseResponse<DetailedInterviewReportVO> getReportById(@RequestParam("id") Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        DetailedInterviewReportVO detailedInterviewReportVO = interviewReportService.getDetailedInterviewReportVO(id);
        return ResultUtils.success(detailedInterviewReportVO);
    }
}
